# 合并两个有序链表: https://leetcode-cn.com/problems/merge-two-sorted-lists/

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

        
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        # 设立一个头结点
        h = ListNode()
        cur = h
        while l1 and l2:
            if l1.val < l2.val:
                p1 = l1
                l1 = l1.next
                cur.next = p1
            else:
                p2 = l2
                l2 = l2.next
                cur.next = p2
            cur = cur.next
    
        # 当其中一个为None了，判断那个不为空，继续添加
        while l1:
            p1 = l1
            l1 = l1.next
            cur.next = p1
            cur = cur.next
         
        while l2:
            p2 = l2
            l2 = l2.next
            cur.next = p2
            cur = cur.next
        
        return h.next
